package com.hankol.newretail.fragment

import android.os.Bundle
import androidx.lifecycle.Observer
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.extension.checkNotNull
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.ToastUtils
import com.baselibrary.activity.BaseFragment
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.newretail.R
import com.hankol.newretail.adapter.HaveEvaluateListAdapter
import com.hankol.newretail.adapter.NeedEvaluateListAdapter
import com.hankol.newretail.bean.EvaluationBean
import com.hankol.newretail.bean.NeedEvaluationBean
import com.hankol.newretail.databinding.FragmentMyOrderBinding
import com.hankol.newretail.viewmodel.EvaluationViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.HashMap

class MyEvaluationFragment(var type: Int = -1) : BaseFragment() {
    private lateinit var binding: FragmentMyOrderBinding
    private lateinit var viewModel: EvaluationViewModel
    private val mNeedEvaluateListAdapter: NeedEvaluateListAdapter by lazy { NeedEvaluateListAdapter() }
    private val mHaveEvaluateListAdapter: HaveEvaluateListAdapter by lazy { HaveEvaluateListAdapter() }
    private var page = 1
    private var hasnext: Boolean = false

    companion object {
        //类型：0待评价，1已评价
        fun newInstance(status: Int = -1): MyEvaluationFragment {
            return MyEvaluationFragment(status)
        }
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        viewModel = getFragmentViewModelProvider(this).get(EvaluationViewModel::class.java)
        binding = getDataBinding<FragmentMyOrderBinding>()
        initView()
        initListener()
        initObserver()
        loadData()
    }


    private fun initObserver() {
        viewModel.myEvaluationDataLD.observe(requireActivity(), Observer {
            binding.smartOrder.finishRefresh()
            binding.smartOrder.finishLoadMore()
            if (type == 0) {
                if (it == null || it.data.isNullOrEmpty()) {
                    mNeedEvaluateListAdapter.setNewData(ArrayList())
                    mNeedEvaluateListAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_EVALUATION_LIST, binding.rvOrderList, "暂无评价")
                } else {
                    if (it.data.checkNotNull()) {
                        hasnext = it.hasnext
                        if (page == 1) {
                            mNeedEvaluateListAdapter.setNewData(transferFirstPageData(it.data))
                        } else {
                            mNeedEvaluateListAdapter.addData(transferMorePageData(it.data))
                        }
                        page++
                    }
                }
                EventBusUtils.sendNotify1Value(MessageBus.msgId_refresh_evaluation_number,it.totalCount)
            } else if (type == 1) {
                if (it == null || it.data.isNullOrEmpty()) {
                    mNeedEvaluateListAdapter.setNewData(ArrayList())
                    mHaveEvaluateListAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_EVALUATION_LIST, binding.rvOrderList, "暂无评价")
                } else {
                    if (it.data.checkNotNull()) {
                        hasnext = it.hasnext
                        if (page == 1) {
                            mHaveEvaluateListAdapter.setNewData(it.data)
                        } else {
                            mHaveEvaluateListAdapter.addData(it.data)
                        }
                        page++
                    }
                }
                EventBusUtils.sendNotify1Value(MessageBus.msgId_refresh_evaluation_number_have, it.totalCount)
            }

        })
    }

    private fun transferFirstPageData(list: List<EvaluationBean>): ArrayList<NeedEvaluationBean> {
        var dataList = ArrayList<NeedEvaluationBean>()
        var data = NeedEvaluationBean()
        data.shopName = list[0].shopName
        data.shopId = list[0].shopId
        data.dealerCode = list[0].dealerCode
        data.needList.add(list[0])
        dataList.add(data)
        if (list.size >= 2) {
            for (i in 1 until list.size) {
                if (list[i].shopName == dataList[dataList.size - 1].shopName) {
                    dataList[dataList.size - 1].needList.add(list[i])
                } else {
                    var data = NeedEvaluationBean()
                    data.shopName = list[i].shopName
                    data.shopId = list[i].shopId
                    data.dealerCode = list[i].dealerCode
                    data.needList.add(list[i])
                    dataList.add(data)
                }
            }
        }
        return dataList
    }

    private fun transferMorePageData(list: List<EvaluationBean>): ArrayList<NeedEvaluationBean> {
        var breakPosition = 0
        for (i in list.indices) {
            if (list[i].shopName == mNeedEvaluateListAdapter.data[mNeedEvaluateListAdapter.data.size - 1].shopName) {
                mNeedEvaluateListAdapter.data[mNeedEvaluateListAdapter.data.size - 1].needList.add(list[i])
                if (i == list.size - 1) {
                    mNeedEvaluateListAdapter.notifyItemChanged(mNeedEvaluateListAdapter.data.size - 1)
                    breakPosition = i
                }
            } else {
                mNeedEvaluateListAdapter.notifyItemChanged(mNeedEvaluateListAdapter.data.size - 1)
                breakPosition = i
                break
            }
        }
        if (breakPosition != list.size - 1) {
            var dataList = ArrayList<NeedEvaluationBean>()
            var data = NeedEvaluationBean()
            data.shopName = list[breakPosition].shopName
            data.shopId = list[breakPosition].shopId
            data.dealerCode = list[breakPosition].dealerCode
            data.needList.add(list[breakPosition])
            dataList.add(data)
            if (list.size >= breakPosition + 2) {
                for (i in breakPosition + 1 until list.size) {
                    if (list[i].shopName == dataList[dataList.size - 1].shopName) {
                        dataList[dataList.size - 1].needList.add(list[i])
                    } else {
                        var data = NeedEvaluationBean()
                        data.shopName = list[i].shopName
                        data.shopId = list[i].shopId
                        data.dealerCode = list[i].dealerCode
                        data.needList.add(list[i])
                        dataList.add(data)
                    }
                }
            }
            return dataList
        } else {
            return ArrayList()
        }
    }

    private fun initView() {
        mHaveEvaluateListAdapter.setOnItemClickListener { adapter, view, position ->
            //进入评价详情页
            val bundle = Bundle()
            bundle.putParcelable("evaluation_detail", mHaveEvaluateListAdapter.data[position])
            ARouterUtils.jump(ActivityRouter.NEW_RETAIL.EVALUATION_DETAIL, bundle)
        }
        binding.rvOrderList.adapter = if (type == 0) mNeedEvaluateListAdapter else mHaveEvaluateListAdapter
    }


    fun loadData() {
        viewModel.requestMyEvaluationList(type, page)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_my_order
    }

    fun initListener() {
        binding.smartOrder.setOnRefreshListener {
            page = 1
            loadData()
        }
        binding.smartOrder.setOnLoadMoreListener {
            if (hasnext) {
                loadData()
            } else {
                binding.smartOrder.finishLoadMore()
            }
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        when (messageBus.codeType) {
            MessageBus.msgId_refresh_evaluation_list -> {
                binding.smartOrder.postDelayed({
                    binding.smartOrder.autoRefresh()
                    binding.rvOrderList.scrollToPosition(0)
                }, 500)

            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}